package rentbook;



import userGUI.DBAccess;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class FerryCargoManagementSystemGUI extends JFrame {
    private JTextField cargoNameField;
    private JTextField cargoTypeField;
    private JTextField cargoLocationField;
    private JTable cargoTable;
    private JButton addButton;
    private JButton updateButton;
    private JButton deleteButton;

    private JButton searchButton;

    public FerryCargoManagementSystemGUI() {
        super("海上渡轮货物承载管理系统");

        // 创建组件
        cargoNameField = new JTextField(20);
        cargoTypeField = new JTextField(20);
        cargoLocationField = new JTextField(20);
        cargoTable = new JTable();
        addButton = new JButton("添加");
        updateButton = new JButton("修改");
        deleteButton = new JButton("删除");

        searchButton = new JButton("搜索");
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchCargo();
            }
        });

        // 设置布局
        setLayout(new BorderLayout());

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new FlowLayout());
        inputPanel.add(new JLabel("货物名称："));
        inputPanel.add(cargoNameField);
        inputPanel.add(new JLabel("货物类型："));
        inputPanel.add(cargoTypeField);
        inputPanel.add(new JLabel("货物位置："));
        inputPanel.add(cargoLocationField);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(searchButton);

        // 添加组件到主界面
        add(inputPanel, BorderLayout.NORTH);
        add(new JScrollPane(cargoTable), BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 设置事件处理
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addCargo();
            }
        });

        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateCargo();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteCargo();
            }
        });

        // 设置窗口属性
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(977, 352);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void searchCargo() {
        String cargoName = cargoNameField.getText().trim();
        String cargoType = cargoTypeField.getText().trim();
        String cargoLocation = cargoLocationField.getText().trim();

        // 构建查询语句
        StringBuilder queryCargoQuery = new StringBuilder("SELECT * FROM cargo WHERE 1=1");
        boolean hasConditions = false;

        // 添加条件：名称
        if (!cargoName.isEmpty()) {
            queryCargoQuery.append(" and name LIKE '%").append(cargoName).append("%'");
            hasConditions = true;
        }

        // 添加条件：类型
        if (!cargoType.isEmpty()) {
            if (hasConditions) {
                queryCargoQuery.append(" AND");
            }
            queryCargoQuery.append(" type LIKE '%").append(cargoType).append("%'");
            hasConditions = true;
        }

        // 添加条件：位置
        if (!cargoLocation.isEmpty()) {
            if (hasConditions) {
                queryCargoQuery.append(" AND");
            }
            queryCargoQuery.append(" location LIKE '%").append(cargoLocation).append("%'");
        }



        try (Connection conn = DBAccess.getConnection()) {
            try (Statement stmt = conn.createStatement()) {
                ResultSet rs = stmt.executeQuery(queryCargoQuery.toString());

                DefaultTableModel model = new DefaultTableModel();
                model.addColumn("ID");
                model.addColumn("名称");
                model.addColumn("类型");
                model.addColumn("位置");

                while (rs.next()) {
                    int cargoId = rs.getInt("id");
                    String name = rs.getString("name");
                    String type = rs.getString("type");
                    String location = rs.getString("location");

                    model.addRow(new Object[]{cargoId, name, type, location});
                }

                cargoTable.setModel(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void addCargo() {
        // 获取输入的货物信息
        String cargoName = cargoNameField.getText();
        String cargoType = cargoTypeField.getText();
        String cargoLocation = cargoLocationField.getText();

        // 在数据库中插入货物信息的代码
        String insertCargoQuery = "INSERT INTO cargo (name, type, location) VALUES ('" +
                cargoName + "', '" + cargoType + "', '" + cargoLocation + "')";

        try (Connection conn = DBAccess.getConnection()) {
            try (Statement stmt = conn.createStatement()) {
                stmt.executeUpdate(insertCargoQuery);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 清空输入框
        cargoNameField.setText("");
        cargoTypeField.setText("");
        cargoLocationField.setText("");

        // 刷新表格显示
        refreshCargoTable();
    }

    private void updateCargo() {
        // 获取选中的表格行
        int selectedRow = cargoTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的货物");
            return;
        }
        int cargoId = (int) cargoTable.getValueAt(selectedRow, 0);
        String cargoName = cargoNameField.getText();
        String cargoType = cargoTypeField.getText();
        String cargoLocation = cargoLocationField.getText();

        String updateCargoQuery = "UPDATE cargo SET name='" + cargoName + "', type='" +
                cargoType + "', location='" + cargoLocation + "' WHERE id=" + cargoId;

        try (Connection conn = DBAccess.getConnection()) {
            try (Statement stmt = conn.createStatement()) {
                stmt.executeUpdate(updateCargoQuery);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        cargoNameField.setText("");
        cargoTypeField.setText("");
        cargoLocationField.setText("");
        // 获取选中行的货物信息

        // 弹出窗口供用户修改货物信息

        // 在数据库中更新货物信息的代码

        // 刷新表格显示
        refreshCargoTable();
    }

    private void deleteCargo() {
        // 获取选中的表格行
        int selectedRow = cargoTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的货物");
            return;
        }

        // 获取选中行的货物信息

        // 在数据库中删除货物信息的代码
        int cargoId = (int) cargoTable.getValueAt(selectedRow, 0);

        String deleteCargoQuery = "DELETE FROM cargo WHERE id=" + cargoId;

        try (Connection conn = DBAccess.getConnection()) {
            try (Statement stmt = conn.createStatement()) {
                stmt.executeUpdate(deleteCargoQuery);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        cargoNameField.setText("");
        cargoTypeField.setText("");
        cargoLocationField.setText("");
        // 刷新表格显示
        refreshCargoTable();
    }

    private void refreshCargoTable() {
        // 从数据库查询货物信息的代码
        String queryCargoQuery = "SELECT * FROM cargo";

        try (Connection conn = DBAccess.getConnection()) {
            try (Statement stmt = conn.createStatement()) {
                ResultSet rs = stmt.executeQuery(queryCargoQuery);

                DefaultTableModel model = new DefaultTableModel();
                model.addColumn("ID");
                model.addColumn("名称");
                model.addColumn("类型");
                model.addColumn("位置");

                while (rs.next()) {
                    int cargoId = rs.getInt("id");
                    String name = rs.getString("name");
                    String type = rs.getString("type");
                    String location = rs.getString("location");

                    model.addRow(new Object[]{cargoId, name, type, location});
                }

                cargoTable.setModel(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 更新表格数据
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FerryCargoManagementSystemGUI();
            }
        });
    }
}
